<template>
  <view class="record-container">
    <!-- 戒烟日期设置 -->
    <view class="quit-date-section">
      <view class="section-title">
        <text>设置戒烟日期</text>
      </view>
      <view class="date-card card">
        <view class="date-picker-wrapper">
          <picker mode="date" :value="quitDate" @change="onDateChange" :end="today">
            <view class="date-picker">
              <view class="date-display">
                <text class="date-text">{{ quitDate || '请选择戒烟开始日期' }}</text>
                <text class="date-icon">📅</text>
              </view>
            </view>
          </picker>
        </view>
        <view class="date-info" v-if="quitDate">
          <view class="info-item">
            <text class="info-label">已戒烟</text>
            <text class="info-value text-primary">{{ quitDays }}</text>
            <text class="info-unit">天</text>
          </view>
          <view class="info-item">
            <text class="info-label">戒烟等级</text>
            <text class="info-value text-success">{{ quitLevel.name }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 吸烟历史设置 -->
    <view class="smoking-history-section">
      <view class="section-title">
        <text>吸烟历史设置</text>
      </view>
      <view class="history-card card">
        <view class="history-form">
          <view class="form-item">
            <text class="form-label">每日吸烟量（支）</text>
            <input 
              class="form-input" 
              type="number" 
              v-model="dailyCigarettes"
              placeholder="请输入每日吸烟支数"
              @blur="saveSmokingHistory"
            />
          </view>
          <view class="form-item">
            <text class="form-label">每包价格（元）</text>
            <input 
              class="form-input" 
              type="digit" 
              v-model="pricePerPack"
              placeholder="请输入每包香烟价格"
              @blur="saveSmokingHistory"
            />
          </view>
          <view class="form-item">
            <text class="form-label">每包支数</text>
            <input 
              class="form-input" 
              type="number" 
              v-model="cigarettesPerPack"
              placeholder="请输入每包香烟支数"
              @blur="saveSmokingHistory"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- 戒烟统计 -->
    <view class="statistics-section" v-if="quitDate">
      <view class="section-title">
        <text>戒烟统计</text>
      </view>
      <view class="stats-grid">
        <view class="stat-card card">
          <view class="stat-icon">💰</view>
          <view class="stat-content">
            <text class="stat-value">¥{{ savedMoney }}</text>
            <text class="stat-label">节省金额</text>
          </view>
        </view>
        <view class="stat-card card">
          <view class="stat-icon">🚭</view>
          <view class="stat-content">
            <text class="stat-value">{{ avoidedCigarettes }}</text>
            <text class="stat-label">避免香烟（支）</text>
          </view>
        </view>
        <view class="stat-card card">
          <view class="stat-icon">⏰</view>
          <view class="stat-content">
            <text class="stat-value">{{ lifeExtended }}</text>
            <text class="stat-label">延长寿命（小时）</text>
          </view>
        </view>
        <view class="stat-card card">
          <view class="stat-icon">🫁</view>
          <view class="stat-content">
            <text class="stat-value">{{ tarAvoided }}</text>
            <text class="stat-label">避免焦油（mg）</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 戒烟里程碑 -->
    <view class="milestones-section" v-if="quitDate">
      <view class="section-title">
        <text>戒烟里程碑</text>
      </view>
      <view class="milestones-card card">
        <view class="milestone-item" 
              v-for="(milestone, index) in milestones" 
              :key="index"
              :class="{ achieved: milestone.achieved, current: milestone.current }">
          <view class="milestone-icon">
            <text>{{ milestone.achieved ? '✅' : milestone.current ? '🔥' : '⏳' }}</text>
          </view>
          <view class="milestone-content">
            <text class="milestone-title">{{ milestone.title }}</text>
            <text class="milestone-desc">{{ milestone.desc }}</text>
            <text class="milestone-time" v-if="!milestone.achieved">
              {{ milestone.remainingDays > 0 ? `还需 ${milestone.remainingDays} 天` : '即将达成' }}
            </text>
          </view>
          <view class="milestone-status">
            <text class="status-text" :class="milestone.achieved ? 'text-success' : 'text-warning'">
              {{ milestone.achieved ? '已达成' : milestone.current ? '进行中' : '未达成' }}
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="actions-section">
      <button class="btn btn-primary action-btn" @click="saveAllData">
        保存设置
      </button>
      <button class="btn btn-warning action-btn" @click="resetData" v-if="quitDate">
        重新开始戒烟
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import type { SmokingHistory, Milestone } from '../../types/global.d.ts'
import { useSmokingHistoryStore } from '@/store/smokingHistory'
import { storeToRefs } from 'pinia'

// 响应式数据
const { quitDate, dailyCigarettes, pricePerPack, cigarettesPerPack } = storeToRefs(useSmokingHistoryStore())
const { setQuitDate, clear: clearSmokingHistory } = useSmokingHistoryStore()
// const smokingHistory = ref<SmokingHistory>({
//   dailyCigarettes: 20,
//   pricePerPack: 15,
//   cigarettesPerPack: 20
// })

// 计算属性
const today = computed((): string => {
  return new Date().toISOString().split('T')[0]
})

const quitDays = computed((): number => {
  if (!quitDate.value) return 0
  const quit = new Date(quitDate.value)
  const now = new Date()
  const diffTime = Math.abs(now.getTime() - quit.getTime())
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
})

const quitLevel = computed(() => {
  const days = quitDays.value
  const levels = [
    { name: '戒烟新手', min: 0, max: 7 },
    { name: '初级戒烟者', min: 8, max: 30 },
    { name: '中级戒烟者', min: 31, max: 90 },
    { name: '高级戒烟者', min: 91, max: 365 },
    { name: '戒烟大师', min: 366, max: 1095 },
    { name: '戒烟专家', min: 1096, max: Infinity }
  ]
  
  return levels.find(level => days >= level.min && days <= level.max) || levels[0]
})

const savedMoney = computed((): string => {
  if (!quitDate.value || quitDays.value === 0) return '0.00'
  const dailyCost = (dailyCigarettes.value / cigarettesPerPack.value) * pricePerPack.value
  return (dailyCost * quitDays.value).toFixed(2)
})

const avoidedCigarettes = computed((): number => {
  if (!quitDate.value || quitDays.value === 0) return 0
  return dailyCigarettes.value * quitDays.value
})

const lifeExtended = computed((): number => {
  if (!quitDate.value || quitDays.value === 0) return 0
  // 每支烟减少11分钟寿命
  const minutesSaved = avoidedCigarettes.value * 11
  return Math.round(minutesSaved / 60)
})

const tarAvoided = computed((): number => {
  if (!quitDate.value || quitDays.value === 0) return 0
  // 每支烟约含10mg焦油
  return avoidedCigarettes.value * 10
})

const milestones = computed((): Milestone[] => {
  const days = quitDays.value
  const milestoneData = [
    { days: 1, title: '戒烟第一天', desc: '开始新的健康生活' },
    { days: 3, title: '坚持三天', desc: '尼古丁开始从体内清除' },
    { days: 7, title: '一周成就', desc: '味觉和嗅觉开始恢复' },
    { days: 14, title: '两周里程碑', desc: '血液循环开始改善' },
    { days: 30, title: '一个月胜利', desc: '肺功能开始改善' },
    { days: 90, title: '三个月成功', desc: '戒断症状基本消失' },
    { days: 365, title: '一年成就', desc: '心脏病风险减半' },
    { days: 1825, title: '五年大师', desc: '中风风险降至非吸烟者水平' }
  ]
  
  return milestoneData.map(milestone => ({
    ...milestone,
    achieved: days >= milestone.days,
    current: days < milestone.days && days >= (milestone.days - 7),
    remainingDays: milestone.days - days
  }))
})

const onDateChange = (e: { detail: { value: string } }): void => {
  setQuitDate(e.detail.value)
}

const saveSmokingHistory = (): void => {
  uni.showToast({
    title: '保存成功',
    icon: 'success'
  })
}

const saveAllData = (): void => {
  uni.showToast({
    title: '保存成功',
    icon: 'success'
  })
}

const resetData = (): void => {
  uni.showModal({
    title: '重新开始戒烟',
    content: '确定要重置所有戒烟数据吗？此操作不可恢复。',
    success: (res) => {
      if (res.confirm) {
        clearSmokingHistory()
        uni.removeStorageSync('checkinData')
        uni.showToast({
          title: '已重置数据',
          icon: 'success'
        })
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.record-container {
  padding: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  margin-bottom: 20rpx;
  color: #333;
}

.date-card {
  .date-picker-wrapper {
    margin-bottom: 30rpx;
    
    .date-picker {
      .date-display {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 20rpx;
        background: #f8f9fa;
        border-radius: 12rpx;
        border: 2rpx solid #e9ecef;
        
        .date-text {
          font-size: 28rpx;
          color: #333;
        }
        
        .date-icon {
          font-size: 32rpx;
        }
      }
    }
  }
  
  .date-info {
    display: flex;
    justify-content: space-around;
    padding-top: 20rpx;
    border-top: 1rpx solid #f0f0f0;
    
    .info-item {
      text-align: center;
      
      .info-label {
        display: block;
        font-size: 24rpx;
        color: #666;
        margin-bottom: 8rpx;
      }
      
      .info-value {
        display: block;
        font-size: 36rpx;
        font-weight: 600;
        margin-bottom: 4rpx;
      }
      
      .info-unit {
        font-size: 22rpx;
        color: #666;
      }
    }
  }
}

.history-card {
  .history-form {
    .form-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 30rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .form-label {
        font-size: 28rpx;
        color: #333;
        flex-shrink: 0;
        margin-right: 20rpx;
      }
      
      .form-input {
        flex: 1;
        height: 80rpx;
        padding: 0 20rpx;
        background: #f8f9fa;
        border-radius: 12rpx;
        border: 2rpx solid #e9ecef;
        font-size: 28rpx;
        text-align: right;
      }
    }
  }
}

.statistics-section {
  margin-bottom: 30rpx;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  
  .stat-card {
    display: flex;
    align-items: center;
    padding: 30rpx 20rpx;
    
    .stat-icon {
      font-size: 48rpx;
      margin-right: 20rpx;
    }
    
    .stat-content {
      flex: 1;
      
      .stat-value {
        display: block;
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .stat-label {
        font-size: 22rpx;
        color: #666;
      }
    }
  }
}

.milestones-section {
  margin-bottom: 30rpx;
}

.milestones-card {
  .milestone-item {
    display: flex;
    align-items: center;
    padding: 25rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    &.achieved {
      opacity: 0.7;
      
      .milestone-content {
        .milestone-title {
          text-decoration: line-through;
        }
      }
    }
    
    &.current {
      background: linear-gradient(90deg, rgba(103, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
      border-radius: 12rpx;
      margin: 0 -20rpx;
      padding: 25rpx 20rpx;
    }
    
    .milestone-icon {
      font-size: 32rpx;
      margin-right: 20rpx;
      width: 60rpx;
      text-align: center;
    }
    
    .milestone-content {
      flex: 1;
      
      .milestone-title {
        display: block;
        font-size: 28rpx;
        font-weight: 500;
        margin-bottom: 8rpx;
      }
      
      .milestone-desc {
        display: block;
        font-size: 24rpx;
        color: #666;
        margin-bottom: 6rpx;
      }
      
      .milestone-time {
        font-size: 22rpx;
        color: #999;
      }
    }
    
    .milestone-status {
      .status-text {
        font-size: 22rpx;
        font-weight: 500;
      }
    }
  }
}

.actions-section {
  padding: 20rpx 0;
  
  .action-btn {
    width: 100%;
    margin-bottom: 20rpx;
    height: 90rpx;
    font-size: 30rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>